import React, { useEffect, useState } from "react";
import { useNavigate, useLocation } from "react-router-dom";
import { Menu } from "antd";
import { findSideBarRoutes } from "@/routes";
export default function Slide({ isFold }) {
  const [openKeys, setOpenKeys] = useState("");
  const [selectedKeys, setSelectedKeys] = useState(""); // 刷新之后仍保存选中
  const navigate = useNavigate();
  const { pathname } = useLocation(); // url
  useEffect(() => {
    // setOpenKeys(pathname);
    setSelectedKeys(pathname);
  }, [pathname]);
  const routes = findSideBarRoutes();
  /**
   * 获取菜单
   */
  function getItem(label, key, icon, children, type) {
    return {
      key,
      icon,
      children,
      label,
      type,
    };
  }
  const menuItems = routes.map((route) => {
    return getItem(
      route.meta?.title,
      route.path,
      route.meta?.icon,
      route.children?.map((item) => {
        if (item.hidden) return null;
        return getItem(item.meta?.title, item.path, item.meta?.icon);
      })
      // .filter(Boolean)
    );
  });

  /**
   * 菜单点击
   * @param {*} key 路由
   */
  const handleMenuClick = ({ key }) => {
    navigate(key);
  };

  return (
    <div
      className="fixed top-[80px] px-[16px] h-[100%]"
      style={{ width: isFold ? 112 : 280 }}
    >
      <Menu
        // openKeys={openKeys}
        selectedKeys={selectedKeys}
        mode="inline"
        inlineCollapsed={isFold}
        items={menuItems}
        style={{ height: "100%", borderRight: 0 }}
        onClick={handleMenuClick}
      />
    </div>
  );
}
